package retrofit2.spring.factory;

import okhttp3.OkHttpClient;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * RetrofitFactoryBean
 *
 * @author archx
 * @since 2020/7/4 7:19
 */
public class RetrofitFactoryBean implements FactoryBean<Retrofit>, InitializingBean {

    private String baseUrl;
    private OkHttpClient client;
    private Converter.Factory converterFactory;

    @Override
    public Class<?> getObjectType() {
        return Retrofit.class;
    }

    @Override
    public Retrofit getObject() throws Exception {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(converterFactory)
                .build();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.hasText(baseUrl, "BaseUrl 必须指定");
        Assert.notNull(client, "OkHttpClient 不能为空");
        Assert.notNull(client, "ConverterFactory 不能为空");
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }

    public void setClient(OkHttpClient client) {
        this.client = client;
    }

    public void setConverterFactory(Converter.Factory converterFactory) {
        this.converterFactory = converterFactory;
    }
}
